$(document).ready(onDocumentReady);

var loggedInUser = null;

function onDocumentReady(){	
	$('#loginForm').ajaxForm({dataType:'xml', beforeSubmit:onBeforeLoginSubmit, success:onLoginSubmitSucces}); 
	$('#registerForm').ajaxForm({dataType:'xml', beforeSubmit:onBeforeRegisterSubmit, success:onRegisterSubmitSucces});

	$("#groupPassItem").fadeTo(0,0.20);
	$("#registerGroupPass")[0].disabled = true;
	
	// try loggin in with the cookie data
	if($.cookie('smoskas')){
	    //decode the cookie and try loggin in with it
		var user = $.evalJSON($.cookie('smoskas'));
	    $('#loginEmail')[0].value = user.email;
	    $('#loginPassword')[0].value = user.password;
	    $('#loginGroupName')[0].value = user.group;
	    $('#loginForm').submit();	    
	}else{
		$.address.init(addressInit);
		$.address.change(addressChange);
	}
}


//LOGIN FORM *********************************************************
function onBeforeLoginSubmit(formData, jqForm, options) {
	formData[0].value = String(formData[0].value).toLowerCase();
	$('#loginEmail')[0].value = formData[0].value;
	
	if(formData[0].value.length < 4){
		showFeedbackString(null, "Please enter a valid email address.");
		return false;
	}
	
	formData[1].value = String(formData[1].value).toLowerCase();
	$('#loginGroupName')[0].value = formData[1].value;
	if(formData[1].value.length < 3){
		showFeedbackString(null, "Please enter a valid group name.");
		return false;
	}

	if(formData[2].value.length < 3){
		showFeedbackString(null, "you entered an invalid password. please try again");
		return false;
	}
	
	if(formData[2].value.length != 32){ //if the password was 32 chars that means it's a hash 
		formData[2].value = $.md5(formData[2].value); 	
	}
	
 	$('#loginForm > input.submit')[0].disabled = true;
    return true; 
}	
function onLoginSubmitSucces(responseXML) { 	
	$('#loginForm > input.submit')[0].disabled = false;
	
	var xml = new JKL.ParseXML("");
	var response = xml.parseElement(responseXML);

    if(response.data.error != undefined){
    	loggedInUser = null;
    	showFeedbackString(null, response.data.error);
    }else{
		//create the cookie when login is succesfull
		loggedInUser = {};
		loggedInUser.email = $('#loginEmail')[0].value;
		if($('#loginPassword')[0].value.length != 32){
			loggedInUser.password = $.md5($('#loginPassword')[0].value);
		}else{
			loggedInUser.password = $('#loginPassword')[0].value;
		}
		loggedInUser.group = $('#loginGroupName')[0].value;		        
		var encodedUser = $.toJSON(loggedInUser);
		$.cookie('smoskas', encodedUser, {expires: 60});
		
		// fill out all login info and show it.
		onQuickLoginDataReceived(response);
		showFeedbackString(response.data.succes);
	}
    $('#loginPassword')[0].value = "";
    
	$.address.init(addressInit);
	$.address.change(addressChange);
	addressInit();
	addressChange();
}

function logout(){
	//delete the cookie
	$.cookie('smoskas', '', { expires: -1 }); // delete cookie
	loggedInUser = null;
}

//REGISTER FORM *******************************************************
function onBeforeRegisterSubmit(formData, jqForm, options) { 
	if(formData[0].value.length < 3){
		showFeedbackString(null, "Please enter your name.");
		return false;
	}
	
	formData[1].value = String(formData[1].value).toLowerCase();
	if(formData[1].value.length < 4){
		showFeedbackString(null, "Please enter a valid email address.");
		return false;
	}
	
	if(formData[2].value.length < 3){
		showFeedbackString(null, "Please enter a longer password.");
		return false;
	}	
	
	formData[3].value = String(formData[3].value).toLowerCase();
	if(formData[3].value.length < 3){
		showFeedbackString(null, "Please enter a valid group name.");
		return false;
	}	
 	formData[2].value = $.md5(formData[2].value);

    //alert('About to submit: \n\n' + formData[0].value + " : "  + formData[1].value + " : "  + formData[2].value + " : "  + formData[3].value); 
    return true; 
}	
function onRegisterSubmitSucces(responseXML) { 
	var xml = new JKL.ParseXML("");
	var response = xml.parseElement(responseXML);
	
	if(response.data.error != undefined && response.data.error != ""){
		showFeedbackString(null, response.data.error);		
	}else 
	if(response.data.succes != undefined && response.data.succes != ""){
		showFeedbackString(response.data.succes);
		$('#loginGroupName')[0].value = $('#registerGroupName')[0].value;
		$('#loginEmail')[0].value = $('#registerEmail')[0].value;
		$('#loginPassword')[0].value = "";
		$('#loginPassword').focus();
		$.address.value("/home/login");
	}else{		
		showFeedbackString(null, toXMLString(responseXML));
	}
	
}

function checkExists(){
	if($("#registerGroupName")[0].value != ""){
		var query = "groupName=" + $("#registerGroupName")[0].value;
		var xml = new JKL.ParseXML("groupExists", query);
		xml.async(onGroupExistsReply);
		xml.parse();
	}else{
		$("#groupPassItem").fadeTo(0,0.15);
		$("#registerGroupPass")[0].disabled = true;
	}
}
function onGroupExistsReply(xmlObject){
	var exists = (xmlObject.data.succes == "true");
	if(exists){
		showFeedbackString("a group with this name exists, enter the group key to join this group. (If a friend invited you, ask him or her for the key.)<br/>If you want to create your own group, pick a different name.");
		$("#groupPassItem").fadeTo(0,1);
		$("#registerGroupPass")[0].disabled = false;
	}else{
		$("#groupPassItem").fadeTo(0,0.15);
		$("#registerGroupPass")[0].disabled = true;
	}
}